package com.youlu.campus.service.jinshuju;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.youlu.campus.base.exception.BusinessException;

import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityQaInfo;
import com.youlu.campus.entity.H5UserPO;
import com.youlu.campus.entity.VO.req.AuthNotifyReq;
import com.youlu.campus.entity.VO.res.AuthNotifyRes;
import com.youlu.campus.entity.WechatH5UserPO;
import com.youlu.campus.entity.jinshuju.JinUserParticipate;
import com.youlu.campus.entity.jinshuju.dto.*;
import com.youlu.campus.service.cache.CacheActivityService;
import com.youlu.campus.service.contest.QQMiniContestService;
import com.youlu.campus.service.data.impl.UvPvService;
import com.youlu.campus.service.system.UserDataPermissionService;
import com.youlu.campus.service.vote.SimpleActivityService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
public class JinShuJuActivityService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private SimpleActivityService simpleActivityService;

    @Autowired
    private QQMiniContestService qqMiniContestService;

    @Autowired
    private UserDataPermissionService userDataPermissionService;

    @Autowired
    private UvPvService uvPvService;
    @Autowired
    private CacheActivityService cacheActivityService;


    public JinShuJuActivityDTO findByActivityId(String activityId) {
        List<String> fields = Lists.newArrayList("id", "rankingTopImgUrl");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        JinShuJuActivityDTO dto = new JinShuJuActivityDTO();
        dto.setRankingTopImgUrl(activityInfo.getRankingTopImgUrl());
        return dto;
    }

    /**
     * 获取报名页活动信息
     *
     * @param activityId
     * @return
     */
    public JinActivitySignUpInfoDTO findSignUpActivityByActivityId(String activityId) {
        List<String> fields = Lists.newArrayList("id", "volunteerWelfareDetail", "signUpNextButtonUrl", "signUpTips");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        JinActivitySignUpInfoDTO dto = new JinActivitySignUpInfoDTO();
        dto.setSignUpNextButtonUrl(activityInfo.getSignUpNextButtonUrl());
        dto.setSignUpTips(activityInfo.getSignUpTips());
        dto.setVolunteerWelfareDetail(activityInfo.getVolunteerWelfareDetail());
        return dto;
    }


    public JinShuJuActivityInviteDTO findInviteInfoByActivityId(String activityId) {
        List<String> fields = Lists.newArrayList("id", "playbillImageUrl", "inviteTips",
                "invitePopupButtonImgUrl", "invitePopupBackgroundImgUrl");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        JinShuJuActivityInviteDTO dto = new JinShuJuActivityInviteDTO();
        dto.setPlaybillImageUrl(activityInfo.getPlaybillImageUrl());
        dto.setInvitePopupBackgroundImgUrl(activityInfo.getInvitePopupBackgroundImgUrl());
        dto.setInvitePopupButtonImgUrl(activityInfo.getInvitePopupButtonImgUrl());
        dto.setInviteTips(activityInfo.getInviteTips());
        return dto;
    }


    public void save(ActivityInfo activityInfo) {
        Date now = new Date();
        activityInfo.setUpdatedTime(now);
        Boolean created = Boolean.FALSE;
        if (StringUtils.isBlank(activityInfo.getId())) {
            activityInfo.setCreatedTime(now);
            created = Boolean.TRUE;
        }
        ActivityInfo save = mongoTemplate.save(activityInfo);

        if (created) {
            List<String> userIds = new ArrayList<>();
            userIds.add(activityInfo.getCreatorId());
            userDataPermissionService.addUserDataPermission(save.getId(), userIds);
        } else {
            cacheActivityService.put(activityInfo);
        }
        if (StringUtils.isBlank(activityInfo.getId())) {
            try {
                //同步活动信息到统计系统
                ActivityQaInfo activityQaInfo = new ActivityQaInfo();
                activityQaInfo.setActivityId(activityInfo.getId());
                activityQaInfo.setActivityName(activityInfo.getName());
                activityQaInfo.setStartTime(activityInfo.getStartTime());
                activityQaInfo.setEndTime(activityInfo.getEndTime());
                uvPvService.doActivityInfo(activityQaInfo);
            } catch (Exception e) {
                log.error("同步活动信息错误:{}", e);
            }
        }

    }

    public QueryJinShuJuIndexDTO queryIndex(String activityId) {
        List<String> fields = Lists.newArrayList("id", "searchButtonImgUrl", "headerImageUrl2",
                "startTime", "endTime", "stop", "stopDetail", "hasShareDy", "douYinUrl", "hasShare",
                "scheduleButton", "registerButton", "wechatAppId");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        QueryJinShuJuIndexDTO queryJinShuJuIndex = new QueryJinShuJuIndexDTO();
        queryJinShuJuIndex.setSearchButtonImgUrl(activityInfo.getSearchButtonImgUrl());
        queryJinShuJuIndex.setHeaderImageUrl2(activityInfo.getHeaderImageUrl2());
        queryJinShuJuIndex.setStatus(qqMiniContestService.getActivityStatus(activityInfo.getEndTime()));
        queryJinShuJuIndex.setStop(activityInfo.getStop());
        queryJinShuJuIndex.setStopDetail(activityInfo.getStopDetail());
        queryJinShuJuIndex.setHasShare(activityInfo.getHasShare());
        queryJinShuJuIndex.setHasShareDy(activityInfo.getHasShareDy());
        queryJinShuJuIndex.setDouYinUrl(activityInfo.getDouYinUrl());
        queryJinShuJuIndex.setRegisterButton(activityInfo.getRegisterButton());
        queryJinShuJuIndex.setScheduleButton(activityInfo.getScheduleButton());
        return queryJinShuJuIndex;
    }

    /**
     * 获取活动其他信息
     *
     * @param activityId
     * @return
     */
    public JinShuJuActivityOtherInfoDTO getOtherInfo(String activityId) {
        List<String> fields = Lists.newArrayList("id", "scheduleButton", "registerButton", "wechatAppId");
        ActivityInfo activityInfo = simpleActivityService.findFieldsById(activityId, fields, ActivityInfo.class);
        if (Objects.isNull(activityInfo)) {
            throw new BusinessException("活动不存在");
        }
        JinShuJuActivityOtherInfoDTO data = new JinShuJuActivityOtherInfoDTO();
        data.setScheduleButton(activityInfo.getScheduleButton());
        data.setRegisterButton(activityInfo.getRegisterButton());
        data.setActivityId(activityId);
        data.setWechatAppId(activityInfo.getWechatAppId());
        return data;
    }

    public AuthNotifyRes getActivitySubInfo(AuthNotifyReq req) {
        log.info(":>>> 开始获取活动订阅信息:{}", JSON.toJSON(req));
        if (!req.getOpenId().contains("h5-")) {
            AuthNotifyRes res = new AuthNotifyRes();
            res.setActivityId(req.getActivityId());
            res.setAppId(req.getAppId());
            res.setOpenId(req.getOpenId());
            log.info(":>>> 请求 openId不包含h5--,||返回结果:{}", JSON.toJSON(res));
            return res;
        }
        String[] arr = req.getOpenId().split("-");
        String mobile = arr[1];
        Query queryJin = new Query();
        queryJin.addCriteria(Criteria.where("mobile").is(mobile).and("activityId").is(req.getActivityId()));
        JinUserParticipate jinUserParticipate = mongoTemplate.findOne(queryJin, JinUserParticipate.class);
        log.info(":>>> 查询用户:{},活动:{} 金数据报名信息为:{}",mobile,req.getActivityId(),JSON.toJSON(jinUserParticipate));
        if (Objects.nonNull(jinUserParticipate)) {
            AuthNotifyRes res = new AuthNotifyRes();
            res.setActivityId(req.getActivityId());
            res.setAppId(req.getAppId());
            res.setOpenId(jinUserParticipate.getOpenId());
            log.info(":>>> JinUserParticipate 存在--:openId:{},||返回结果:{}", jinUserParticipate.getOpenId(),JSON.toJSON(res));
            return res;
        }
        log.info(":>>> 请求 openId包含h5--,||进行反查处理");
        Query query1 = new Query(Criteria.where("openId").is(req.getOpenId()));
        H5UserPO h5UserPO = mongoTemplate.findOne(query1, H5UserPO.class);
        if (Objects.isNull(h5UserPO)) {
            AuthNotifyRes res = new AuthNotifyRes();
            res.setActivityId(req.getActivityId());
            res.setAppId(req.getAppId());
            res.setOpenId(req.getOpenId());
            log.info(":>>> h5UserPO 不存在--:openId:{},||返回结果:{}", req.getOpenId());
            return res;
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("accountInfoId").is(h5UserPO.getAccountInfoId()).
                and("appId").is(req.getAppId()));
        WechatH5UserPO wechatH5UserPO = mongoTemplate.findOne(query, WechatH5UserPO.class);
        if (wechatH5UserPO == null) {
            AuthNotifyRes res = new AuthNotifyRes();
            res.setActivityId(req.getActivityId());
            res.setAppId(req.getAppId());
            res.setOpenId(req.getOpenId());
            log.info(":>>> wechatH5UserPO 不存在--:accountInfoId:{},appId:{},||返回结果:{}", h5UserPO.getAccountInfoId(), req.getAppId(), JSON.toJSON(res));
            return res;
        }
        AuthNotifyRes res = new AuthNotifyRes();
        res.setActivityId(req.getActivityId());
        res.setAppId(req.getAppId());
        res.setOpenId(wechatH5UserPO.getOpenId());
        log.info(":>>> wechatH5UserPO存在--:userId:{},||返回结果:{}", h5UserPO.getAccountInfoId());
        return res;

    }
}
